def compressMethod(lsbs: list[str]) -> list[bytes, int, int]:
    """
    使用游程编码（RLE）压缩二进制序列
    :param lsbs: 字符 '0' 和 '1' 组成的列表
    :return: 原始字节数、压缩后字节数、压缩比、压缩后的字节数据
    """
    lsbsStr = "".join(lsbs)  # 拼接成字符串

    # === RLE 编码过程 ===
    if not lsbsStr:
        compressed_bytes = b""
    else:
        rle_pairs = []  # 存储 (bit, count)
        current_bit = lsbsStr[0]
        count = 1

        for bit in lsbsStr[1:]:
            if bit == current_bit:
                count += 1
            else:
                rle_pairs.append((current_bit, count))
                current_bit = bit
                count = 1
        rle_pairs.append((current_bit, count))  # 添加最后一段

        # 将 RLE 结果打包成字节流
        # 每个条目：1 字节表示 bit ('0'/'1') + 4 字节表示 count（小端）
        import struct

        compressed_data = b""
        for bit_char, cnt in rle_pairs:
            # bit 用 0 或 1 表示
            bit_val = 0 if bit_char == "0" else 1
            compressed_data += struct.pack(
                "<BI", bit_val, cnt
            )  # <: 小端, B: unsigned char, I: unsigned int
        compressed_bytes = compressed_data

    # 转原始数据为字节（用于对比）
    def bin_str_to_bytes(s):
        s = s.ljust((len(s) + 7) // 8 * 8, "0")  # 补齐到8的倍数
        return bytes([int(s[i : i + 8], 2) for i in range(0, len(s), 8)])

    original_data = bin_str_to_bytes(lsbsStr)
    original_size = len(original_data)
    compressed_size = len(compressed_bytes)

    # print(f"RLE 压缩前: {original_size} 字节")
    # print(f"RLE 压缩后: {compressed_size} 字节")
    # if original_size > 0:
    #     ratio = compressed_size / original_size
    #     print(f"压缩比: {ratio:.2f}")
    # else:
    #     print(f"压缩比: N/A")

    return compressed_bytes, original_size, compressed_size


def decompress_rle(compressed_bytes: bytes, total_expected_bits: int = None)-> list[str]:
    import struct

    result = []
    i = 0
    while i < len(compressed_bytes):
        # 每次读取 5 字节：1 byte bit + 4 byte count
        bit_val = struct.unpack("<B", compressed_bytes[i : i + 1])[0]
        count = struct.unpack("<I", compressed_bytes[i + 1 : i + 5])[0]
        i += 5
        bit_char = "1" if bit_val == 1 else "0"
        result.append(bit_char * count)
    return "".join(result)


if __name__ == "__main__":
    # 示例调用
    lsbs = ["1"] * 100 + ["0"] * 200 + ["1"] * 50 + ["0"] * 300  # 典型游程序列
    compressMethod(lsbs)

    # 示例验证
    compressed, _, _ = compressMethod(["1"] * 100 + ["0"] * 200)
    decompressed = decompress_rle(compressed)
    print(
        "解压正确:",
        len(decompressed) >= 300
        and decompressed[:100] == "1" * 100
        and decompressed[100:300] == "0" * 200,
    )
